<?php

namespace app\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Db;
use app\model\Site;
use think\facade\Session;
use think\facade\Request;
use app\utils\Utils;
use think\facade\Cache;
use app\model\User as UserModel;
use app\model\Log;


class User extends BaseController
{
    static public function index($i = 1) // 页面
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        $users = UserModel::where('id', $i)->select()->toArray(); // 查询数据
        if (count($users) == 0) {
            http_response_code(404);
            return View::fetch(Site::get('template') . '/404');
        }
        if ($my_user_info['id'] == intval($i)) { // 是本人
            $isme = true;
        } else {
            $isme = false;
        }
        $user = $users[0];

        $posts = Db::connect()->table('site_post')->where('user_id', $i)->select()->toArray(); // 查询帖子数据
        if (count($posts) == 0) {
            $result = false;
        } else {
            $result = array();
            foreach ($posts as $key) {
                $key["text"] = mb_strimwidth($key["text"], 0, 150, '...', "utf-8");
                $key["time"] = date('Y-m-d', $key["time"]);
                $result[] = $key;
            }
        }
        return View::fetch(Site::get("template") . '/user', [
            'img'  => Site::get("img"),
            'about' => Site::get('about'),
            'title' => Site::get("title"),
            'navitems' => Site::get('navitems'),
            'my_name' => $my_user_info['name'],
            'my_img' => $my_user_info['img'],
            'my_email' => $my_user_info['email'],
            'my_id' => $my_user_info['id'],
            'user_name' => $user["name"],
            'user_email' => $user["email"],
            'user_img' => $user["img"],
            'user_id' => $user["id"],
            'user_time' => date('Y-m-d H:i:s', $user["time"]),
            'isme' => $isme,
            'post' => $result,
            'logo' => Site::get("logo"),
            'url' => Site::get("url"),
            'header' => Site::get("header"),
            'footer' => Site::get("footer"),
            'footer_about' => Site::get("footer_about"),
            'footer_list' => Site::get('footer_list')
        ]);
    }

    static public function set_bcmid() // 绑定api
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        if ($my_user_info['id'] == '') {
            //未登录
            return json(array("code" => 403, 'msg' => '未登录'));
        }
        $telephone_number = Request::post('identity', false);
        $password = Request::post('password', false);

        if (!$telephone_number || !$password) {
            return json(array("code" => 404, 'msg' => '参数有误'));
        } else {
            $email_time = Cache::get($telephone_number, false);
            if (!$email_time) {
                // 不存在当前账号的时间限制缓存
                // 缓存在10秒之后过期
                Cache::set($telephone_number, time(), 15);
                $info =  json_decode(Utils::bcm_login($telephone_number, $password), true);
                if (array_key_exists("auth", $info) && array_key_exists("user_info", $info)) {
                    //验证成功

                    $user = UserModel::where('bcm_id', $info['user_info']['id'])->select()->toArray(); // 查询数据

                    if (count($user) == 0) {
                        // 不存在该账户
                        UserModel::where('id', $my_user_info['id'])->save([
                            'bcm_id' => $info['user_info']['id'],
                        ]);
                        return json(array("code" => 200, 'msg' => '绑定成功'));
                    } else {
                        // 存在关联账户
                        // 设置session
                        return json(array("code" => 403, 'msg' => '此账号已被关联'));
                    }
                } else {
                    //验证失败
                    return json(array("code" => 403, 'msg' => '账号不存在或密码错误'));
                }
            } else {
                // 存在账号登录时间缓存文件
                if ($email_time + 10 < time()) {
                    // 不存在当前账号的时间限制缓存
                    // 缓存在10秒之后过期
                    Cache::set($telephone_number, time(), 15);
                    $info =  json_decode(Utils::bcm_login($telephone_number, $password), true);
                    if (array_key_exists("auth", $info) && array_key_exists("user_info", $info)) {
                        // 验证成功

                        $user = UserModel::where('bcm_id', $info['user_info']['id'])->select()->toArray(); // 查询数据

                        if (count($user) == 0) {
                            // 不存在该账户
                            UserModel::where('id', $my_user_info['id'])->save([
                                'bcm_id' => $info['user_info']['id'],
                            ]);
                            return json(array("code" => 200, 'msg' => '绑定成功'));
                        } else {
                            // 存在关联账户
                            // 设置session
                            return json(array("code" => 403, 'msg' => '此账号已被关联'));
                        }
                    } else {
                        // 验证失败
                        return json(array("code" => 403, 'msg' => '账号不存在或密码错误'));
                    }
                } else {
                    // 等待
                    return json(array("code" => 403, 'msg' => '请稍等一会哦~'));
                }
            }
        }
    }

    static public function get_status()
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $info = Utils::user($email, $pw);

        if (!$info) return Utils::api_response(500, "获取失败");
        if ($info['id'] == '') return Utils::api_response(401, "未登录");

        $group = Db::table('site_user_group_user_list')->where('user_id', $info['id'])->select()->toArray();
        // 查询用户组的数据
        $groupItems = array();
        foreach ($group as $item) {
            $groupItem = Db::table('site_user_group')->where('id', $item['group_id'])->select()->toArray();
            $groupItems[] = array(
                "id" => $groupItem[0]['id'],
                "title" => $groupItem[0]['title']
            );
        }

        return Utils::api_response(200, "获取成功", array(
            "id" => $info['id'],
            "name" => $info['name'],
            "img" => $info['img'],
            "group" => $groupItems
        ));
    }

    static public function get_posts()
    {
        $user_id = Request::post('user_id', false);
        $code = 200;
        $msg = "获取成功";

        $posts = Db::connect()->table('site_post')->where('user_id', $user_id)->order(['time' => 'desc'])->select()->toArray(); // 查询帖子数据
        $result = array();
        foreach ($posts as $key) {
            unset($key['ip']);
            $key['text'] = mb_substr($key['text'], 0, 100, "utf-8");
            $result[] = $key;
        }
        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $result;
        }
        return json($re);
    }

    static public function set_pw() // 忘记密码（请先发送验证码请求）
    {
        $email = Request::post('email', false);
        $post_code = Request::post('code', false);
        $password = Request::post('password', false);

        if (!$post_code || !$password || !$email) {
            // 缺少值
            return json(array("code" => 404, 'msg' => '参数有误'));
        } else { // 已获取参数
            $user = UserModel::where('email', $email)->select()->toArray(); // 查询数据
            if (count($user) == 0) {
                // 没有此用户
                return json(array("code" => 404, 'msg' => '账号不存在'));
            }
            $email_time = Cache::get($email, false);
            if (!$email_time) { // 不存在账号缓存
                // 缓存在10秒之后过期
                Cache::set($email, time(), 15);
                // 查询验证码
                $code = Db::connect()->table('site_code')->where('email', $email)->select()->toArray(); // 查询数据

                if (count($code) == 0) { // 不存在
                    return json(array("code" => 403, 'msg' => '请先发送验证码')); // 没有验证码
                } else {
                    if ($code[0]['code'] == $post_code && $code[0]['time'] + 300 > time()) { // 验证码正确
                        $password = hash("sha256", $password);
                        UserModel::where('id', $user[0]['id'])->save([
                            'password' => $password
                        ]);
                        return json(array("code" => 200, 'msg' => '更换成功'));
                    } else {
                        return json(array("code" => 403, 'msg' => '验证码错误')); // 没有验证码
                    }
                }
            } else {
                // 存在账号缓存
                if ($email_time + 10 < time()) {
                    // 缓存在10秒之后过期
                    Cache::set($email, time(), 15);
                    // 查询验证码
                    $code = Db::connect()->table('site_code')->where('email', $email)->select()->toArray(); // 查询数据

                    if (count($code) == 0) { // 不存在
                        return json(array("code" => 403, 'msg' => '请先发送验证码')); // 没有验证码
                    } else {
                        if ($code[0]['code'] == $post_code && $code[0]['time'] + 300 > time()) { // 验证码正确
                            $password = hash("sha256", $password);
                            UserModel::where('id', $user[0]['id'])->save([
                                'password' => $password
                            ]);
                            return json(array("code" => 200, 'msg' => '更换成功'));
                        } else {
                            return json(array("code" => 403, 'msg' => '验证码错误')); // 没有验证码
                        }
                    }
                } else {
                    // 需要等待
                    return json(array("code" => 403, 'msg' => '请稍等一会哦~'));
                }
            }
        }
    }

    static public function set_info()
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);
        if ($my_user_info['id'] == '') {
            //未登录
            return json(array("code" => 403, 'msg' => '未登录'));
        }
        //$name = Request::post('name', false);
        $img = Request::post('img', false);
        
        /*
        if (mb_strlen($name) > 50 || mb_strlen($img) > 8182) { // 长度过大
            return json(['code' => 400, 'msg' => '字数过多']);
        }*/

        if (!$img) {
            // 缺少值
            return json(array("code" => 404, 'msg' => '参数有误'));
        } else {

            // 如果要更改昵称并且昵称已经存在
            /*if ($my_user_info['name'] !== $name && UserModel::hasName($name)) {
                return json(array("code" => 400, 'msg' => '昵称已存在'));
            }*/

            UserModel::where('id', $my_user_info['id'])->save([
                'img' => $img
            ]);

            return json(array("code" => 200, 'msg' => '保存成功'));
        }
    }

    static public function get_group($i = 0)
    {
        return json(Db::table('site_user_group')->where('id', $i)->select()->toArray());
    }

    static public function protect_user()
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);
        Session::clear();
        if ($my_user_info['id'] == '') {
            //未登录
            return json(array("code" => 403, 'msg' => '未登录'));
        }
        Cache::set(md5("uid_" . $my_user_info['id']), true, 3600);
        $token = Db::table('site_token')->where('user_id', $my_user_info['id'])->select()->toArray();
        foreach ($token as $key) {
            //过滤token的非法字符，只允许字母和数字
            $key["token"] = preg_replace('/[^a-zA-Z0-9]/', '', $key["token"]);
            unlink("../runtime/session/sess_" . $key["token"]);
        }
        Db::table('site_token')->where('user_id', $my_user_info['id'])->delete();
        return json(array("code" => 200, 'msg' => '保护成功'));
    }

    static public function get_group_tree($user_id)
    {
        return json(Utils::getUserGroupTree($user_id));
    }
}
